package com.jiashihui.web.config;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

/**
 * 获取当前项目端口号
 */
@Component
public class IpConfiguration implements ApplicationListener<WebServerInitializedEvent> {

    private int serverPort;

    private String ip;

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }

    public int getPort() {
        return this.serverPort;
    }

    public String getIp() throws SocketException {
        return getLocalIpAddr().get(0);
    }

    private ArrayList<String> getLocalIpAddr() throws SocketException {
        ArrayList<String> ipList = new ArrayList<String>();
        Enumeration interfaces= NetworkInterface.getNetworkInterfaces();
        while(interfaces.hasMoreElements()) {
            NetworkInterface ni=(NetworkInterface)interfaces.nextElement();
            Enumeration ipAddrEnum = ni.getInetAddresses();
            while(ipAddrEnum.hasMoreElements()) {
                InetAddress addr = (InetAddress)ipAddrEnum.nextElement();
                if (addr.isLoopbackAddress() || addr.getHostAddress().contains(":")) {
                    continue;
                }
                ipList.add(addr.getHostAddress());
            }
        }
        Collections.sort(ipList);
        return ipList;
    }
}

/**
 * Spring Boot 2.0.0 M1之前获取本项目端口的方法
 */
//@Configuration
//public class ServiceInfoUtil implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
//    private static EmbeddedServletContainerInitializedEvent event;
//
//    @Override
//    public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
//        ServiceInfoUtil.event = event;
//    }
//
//    public static int getPort() {
//        Assert.notNull(event);
//        int port = event.getEmbeddedServletContainer().getPort();
//        Assert.state(port != -1, "端口号获取失败");
//        return port;
//    }
//}

/**
 * 获取ip地址 linux 有时候获取到的是127.0.0.1
 */
//try {
//        InetAddress ip4 = Inet4Address.getLocalHost();
//        System.out.println(ip4.getHostAddress());
//   } catch (UnknownHostException e) {
//        e.printStackTrace();
//}
